const app = getApp();
const api = require("../../../config/api");
const requestUtil = require("../../../utils/request");

Page({
  data: {
    TabCur: 0, // 左侧选择项（index）
    VerticalNavTop: 0, // 窗口高度
    SelectedStudentId: null, // 被选学生id
    SelectedStudentName: null, // 被选学生名字
    load: true,
    studentList: null, // 学生列表
    subjectMap: null, // 科目英文成绩数组
    subjectArray: [], // 科目数组
    params: null,
  },

  onLoad(options) {
    let params = {
      grade: options.grade,
      clazz: options.clazz,
      studyType: options.studyType,
      schoolId: app.globalData.teacherInfo[0].schoolId,
      examId: options.examId,
      teacherId: app.globalData.teacherInfo[0].id,
    }
    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    //TODO 是不是要让胡工给我个接口获取科目啊？
    let subjectArray = ['语文', '数学', '英语'];
    // 学科英文名对照表
    let subjectMap = [];
    for (let i of subjectArray) {
      subjectMap.push(app.globalData.subjectEnglishNameMap().get(i) + 'Score');
    }
    this.setData({
      subjectMap,
      subjectArray,
      params
    });

    // 获取学生列表
    this.getStudentsList(params);
  },

  onReady() {
    wx.hideLoading()
  },

  async getStudentsList(params) {
    // 获取学生列表
    let res = await requestUtil.request("POST", api.getClassStudentList, params);
    // 获取成绩列表
    let scoreRes = await requestUtil.request("POST", api.getClassStudentExamScore, params);
    let studentList = res.data.data;
    let scoreList = scoreRes.data.data;
    let subjectMap = this.data.subjectMap;
    let studentInfoList = []
    // 过滤了一些无用数据，可加快页面渲染
    for (let i of studentList) {
      let obj = {
        id: i.id,
        clazz: i.clazz,
        grade: i.grade,
        gradeName: i.gradeName,
        name: i.name,
        schoolId: i.schoolId,
        studyType: i.studyType
      }
      for (let j = 0; j < scoreList.length; j++) {
        if (i.id == scoreList[j].studentId) {
          for (let m = 0; m < subjectMap.length; m++) {
            let score = scoreList[j][subjectMap[m]];
            if (score != null && score != "") {
              obj[subjectMap[m]] = score;
            }
          }
        }
      }
      studentInfoList.push(obj);
    }
    studentInfoList.unshift({
      name: '提交成绩',
      id: 0,
    })
    this.setData({
      studentList: studentInfoList,
      SelectedStudentId: studentInfoList[0].id,
      SelectedStudentName: studentInfoList[0].name,
    })

  },

  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.index,
      SelectedStudentId: e.currentTarget.dataset.id,
      SelectedStudentName: e.currentTarget.dataset.name,
      VerticalNavTop: (e.currentTarget.dataset.index - 1) * 50
    })
  },

  async submit(e) {
    let allValue = e.detail.value;
    let studentList = this.data.studentList.slice(1); // 去掉第一个元素
    let subjectMap = this.data.subjectMap;
    let params = this.data.params;
    let studentIds = [];
    let scoreList = [];
    let list = [];
    for (let i of studentList) {
      studentIds.push(i.id);
      list.push({
        "studentName": i.name
      });
    }
    for (let j in list) {
      let sum = 0; // 统计有几个项为空
      for (let k of subjectMap) {
        let item = studentIds[j] + '-' + k;
        if (allValue[item] != '' && typeof (allValue[item]) !== 'undefined') {
          list[j][k] = allValue[item]
        } else {
          sum++;
        }
      }
      // 如果空input数不等于科目数，即此学生有修改成绩，添加到结果里
      if (sum != subjectMap.length) {
        scoreList.push(list[j])
      }
      sum = 0; // 最后把它重置
    }
    if (scoreList == null || !scoreList.length > 0) {
      wx.showToast({
        title: '请先填写学生成绩',
        icon: 'none'
      })
      return;
    }
    let data = {
      schoolId: params.schoolId,
      examId: params.examId,
      clazz: params.clazz,
      teacherId: params.teacherId,
      scoreList: scoreList
    }
    let importResult = await requestUtil.request('POST', api.importScore, data);
    if (importResult.data.code == 0) {
      wx.showToast({
        title: '数据已全部提交',
      })
    } else {
      wx.showToast({
        title: '上传失败，' + importResult.data.msg,
        icon: 'none'
      })
    }
  },
})